<?php
// +----------------------------------------------------------------------
// | 验证器
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\validate;

use think\Validate;

/**
 * 系统用户验证器
 *
 * Class SystemUsersValidate
 * @package app\validate
 */
class SystemUsersValidate extends Validate
{
    // 验证规则
    protected $rule =   [
        'depts'     => 'checkArray:部门',
        'roles'     => 'checkArray:角色',
        'username'  => 'require|max:25|unique:system_users',
        'nickname'  => 'require|max:25',
        'password'  => 'require|checkPassword',
        'phone'     => 'max:100',
        'email'     => 'max:100',
        'remark'    => 'max:255',
    ];

    // 错误消息
    protected $message  =   [
        'username.require'       => '账号名不能为空',
        'username.max'           => '账号名最多不能超过25个字符',
        'username.unique'        => '账号名重复',
        'nickname.require'       => '昵称不能为空',
        'nickname.max'           => '昵称最多不能超过25个字符',
        'password.require'       => '密码不能为空',
        'password.checkPassword' => '密码格式应为8 - 18位数字、字母、符号的任意两种组合',
        'phone.max'              => '手机格式有误',
        'email.max'              => '邮箱格式有误',
        'remark.max'             => '备注最多不能超过255个字符',
    ];

    // 验证场景
    protected $scene = [
        // 修改密码
        'password'   => ['password'],
        // 修改角色
        'roles'      => ['roles'],
        // 后台新增
        'admin_add'  => ['depts', 'username', 'nickname', 'password', 'phone', 'email', 'remark'],
        // 后台修改
        'admin_edit' => ['depts', 'username', 'nickname', 'phone', 'email', 'remark'],
        // 个人修改
        'self_edit'  => ['nickname', 'phone', 'email', 'remark'],
    ];

    // 自定义验证规则
    protected function checkArray($value, $rule, $data = [])
    {
        if (!is_array($value)) {
            return $rule . '选择有误';
        }
        foreach ($value as $v) {
            if (!is_int($v)) {
                return $rule . '选择有误';
            }
        }
        return true;
    }

    protected function checkPassword($value)
    {
        $pattern = '/^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,18}$|^(?=.*[0-9])(?=.*[!@#$%^&*]).{8,18}$|^(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,18}$/';
        return preg_match($pattern, $value) === 1;
    }
}
